<?php

namespace app\admin\controller;

use app\admin\model\Project;
use app\common\controller\Backend;
use Exception;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Shared\Converter;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 专家抽取记录
 *
 * @icon fa fa-circle-o
 */
class Projectexpert extends Backend
{

    /**
     * Projectexpert模型对象
     * @var \app\admin\model\Projectexpert
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Projectexpert;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index($ids = '')
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->alias('u')
            ->where($where)
            ->field('e.name,e.id as eid,u.*,e.professional,e.contact_tel')
            ->join('fa_expert e', 'u.expert_id = e.id')
            ->order($sort, $order)
            ->where('u.project_id', $ids)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 拒绝
     */
    public function refuse($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $result = false;
        $pModel = new Project();
        // $projectInfo = $pModel->where('id', $row['project_id'])->find();
        // if ($projectInfo['status'] == 3) {
        //     $this->error("项目已完成，不能操作");
        // }

        $params['status'] = 3;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
            $pModel->updateProjectStatus($row['project_id']);
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 同意
     */
    public function agree($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $result = false;

        $pModel = new Project();
        $projectInfo = $pModel->where('id', $row['project_id'])->find();
        if ($projectInfo['status'] == 3) {
            $this->error("项目已完成，不能操作");
        }

        $params['status'] = 2;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
            $pModel->updateProjectStatus($row['project_id']);
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function print1($ids = '')
    {
        try {
            // 创建 PHPWord 实例
            $phpWord = new PhpWord();
            $projectInfo = Db::name('project')->where('id', $ids)->find();
            $project_title = $projectInfo['name'];
            // 添加一个 section（页面）
            $section = $phpWord->addSection();
            $phpWord->addFontStyle('titlestyle', array('bold' => true, 'size' => 24)); //标题的样式
            $section->addText('关于' . $project_title . '项目', 'titlestyle', ['alignment' => 'center']);
            $section->addText('专家抽取结果', 'titlestyle', ['alignment' => 'center']);

            // 添加页眉
            $header = $section->addHeader();
            // 添加一个段落到页眉中 
            $headerParagraph = $header->addText($projectInfo['agent']);
            $header->addTextBreak(); // 添加一个换行符以便分隔内容和横线
            $header->addLine(array('width' => Converter::cmToPixel(11.9), 'color'=>'#C0C0C0','height' => Converter::cmToPixel(0.01), 'positioning' => 'absolute')); // 添加横线，宽度和高度可以根据需要调整 // 添加横线 
            // 设置页眉样式，例如居中
            $headerParagraph->setParagraphStyle(array('alignment' => 'center'));
            
            // 添加一个 4列3行的表格（包含表头）
            $table = $section->addTable([
                'borderSize' => 10,          // 边框大小
                'borderColor' => '000000',   // 边框颜色（黑色）
                'cellMargin' => 80,         // 单元格边距
                'alignment' => 'center'     // 表格居中
            ]);

            // 定义表头样式
            $headerStyle = [
                // 'bgColor' => 'CCCCCC',      // 背景颜色（灰色）
                'bold' => true,             // 加粗
                'alignment' => 'center'     // 文字居中
            ];

            // 定义内容样式
            $cellStyle = [
                'alignment' => 'center',
                'valign' => 'center'
            ];

            // 添加表头
            $table->addRow(400); // 行高400 twips（20磅） 
            $table->addCell(2000, $headerStyle)->addText('序号', [], ['alignment' => 'center']);
            $table->addCell(3000, $headerStyle)->addText('姓名', [], ['alignment' => 'center']);
            $table->addCell(4500, $headerStyle)->addText('联系电话', [], ['alignment' => 'center']);
            $table->addCell(4000, $headerStyle)->addText('工作单位', [], ['alignment' => 'center']);
            $table->addCell(4000, $headerStyle)->addText('专家分类', [], ['alignment' => 'center']);
            $table->addCell(2000, $headerStyle)->addText('抽取方式', [], ['alignment' => 'center']);
            $table->addCell(4000, $headerStyle)->addText('抽取时间', [], ['alignment' => 'center']);
            $table->addCell(5000, $headerStyle)->addText('短信通知时间', [], ['alignment' => 'center']);

            $expertData = $this->model
                ->alias('u')
                ->field('e.*,u.createtime as cq_time,u.send_time')
                ->join('fa_expert e', 'u.expert_id = e.id')
                ->where('u.status', 2)
                ->where('u.project_id', $ids)
                ->select();
            if (empty($expertData)) {
                return json(['code' => 0, 'msg' => '没有专家信息']);
            }

            $print_data = [];
            foreach ($expertData as $k => $v) {
                $send_time = $v['send_time'] ? date('Y-m-d H:i:s', $v['send_time']) : '无';
                array_push($print_data, [$k + 1, $v['name'], $v['contact_tel'], $v['work_unit'], $v['professional'], '正常抽取', date('Y-m-d H:i:s', $v['cq_time']), $send_time]);
            }

            foreach ($print_data as $row) {
                $table->addRow();
                foreach ($row as $cell) {
                    $table->addCell(null, $cellStyle)->addText($cell);
                }
            }
            // 保存文件
            $filename = 'world/专家抽取结果-同正项目管理有限公司.docx';
            $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
            $objWriter->save($filename);

            // 检查是否通过HTTPS访问
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://';
            // 获取主机名
            $host = $_SERVER['HTTP_HOST'];
            // 组合成完整的URL
            $currentDomain = $protocol . $host;
            return json(['code' => 1, 'msg' => '打印成功', 'data' => $currentDomain . '/' . $filename]);
        } catch (Exception $e) {
            echo $e->getMessage();
            return json(['code' => 0, 'msg' => '打印失败']);
            // die('生成文档失败: ' . $e->getMessage());
        }
    }

    public function print($ids = '')
    {
        try {
            // 创建 PHPWord 实例
            $phpWord = new PhpWord();
            $projectInfo = Db::name('project')->where('id', $ids)->find();
            if (time() - $projectInfo['open_time'] < 900) {
                return json(['code' => 0, 'msg' => '未到开标时间后15分钟无法打印']);
            }
            $project_title = $projectInfo['name'];
            // 添加一个 section（页面）


            $section = $phpWord->addSection();
            $phpWord->addFontStyle('titlestyle', array('bold' => true, 'size' => 24)); //标题的样式
            $section->addText('关于' . $project_title . '项目', 'titlestyle', ['alignment' => 'center']);
            $section->addText('专家抽取结果', 'titlestyle', ['alignment' => 'center']);


            // 添加页眉
            $header = $section->addHeader();
            // 添加一个段落到页眉中 
            $headerParagraph = $header->addText($projectInfo['agent']);
            $header->addTextBreak(); // 添加一个换行符以便分隔内容和横线
            $header->addLine(array('width' => Converter::cmToPixel(11.9), 'color'=>'#C0C0C0','height' => Converter::cmToPixel(0.01), 'positioning' => 'absolute')); // 添加横线，宽度和高度可以根据需要调整 // 添加横线 
            // 设置页眉样式，例如居中
            $headerParagraph->setParagraphStyle(array('alignment' => 'center'));



            // 添加一个 4列3行的表格（包含表头）
            $table = $section->addTable([
                'borderSize' => 10,          // 边框大小
                'borderColor' => '000000',   // 边框颜色（黑色）
                'cellMargin' => 80,         // 单元格边距
                'alignment' => 'center'     // 表格居中
            ]);

            // 定义表头样式
            $headerStyle = [
                // 'bgColor' => 'CCCCCC',      // 背景颜色（灰色）
                'bold' => true,             // 加粗
                'alignment' => 'center'     // 文字居中
            ];

            // 定义内容样式
            $cellStyle = [
                'alignment' => 'center',
                'valign' => 'center'
            ];

            // 添加表头
            $table->addRow(400); // 行高400 twips（20磅） 
            $table->addCell(2000, $headerStyle)->addText('序号', [], ['alignment' => 'center']);
            $table->addCell(3000, $headerStyle)->addText('姓名', [], ['alignment' => 'center']);
            $table->addCell(4500, $headerStyle)->addText('联系电话', [], ['alignment' => 'center']);
            $table->addCell(4000, $headerStyle)->addText('工作单位', [], ['alignment' => 'center']);
            $table->addCell(4000, $headerStyle)->addText('专家分类', [], ['alignment' => 'center']);
            $table->addCell(2000, $headerStyle)->addText('抽取方式', [], ['alignment' => 'center']);
            $table->addCell(4000, $headerStyle)->addText('抽取时间', [], ['alignment' => 'center']);
            $table->addCell(5000, $headerStyle)->addText('短信通知时间', [], ['alignment' => 'center']);

            $expertData = $this->model
                ->alias('u')
                ->field('e.*,u.createtime as cq_time,u.send_time')
                ->join('fa_expert e', 'u.expert_id = e.id')
                ->where('u.status', 2)
                ->where('u.project_id', $ids)
                ->select();
            if (empty($expertData)) {
                return json(['code' => 0, 'msg' => '没有专家信息']);
            }

            $print_data = [];
            foreach ($expertData as $k => $v) {
                $send_time = $v['send_time'] ? date('Y-m-d H:i:s', $v['send_time']) : '无';
                array_push($print_data, [$k + 1, $v['name'], $v['contact_tel'], $v['work_unit'], $v['professional'], '正常抽取', date('Y-m-d H:i:s', $v['cq_time']), $send_time]);
            }

            foreach ($print_data as $row) {
                $table->addRow();
                foreach ($row as $cell) {
                    $table->addCell(null, $cellStyle)->addText($cell);
                }
            }
            // 保存文件
            $filename = 'world/专家抽取结果-同正项目管理有限公司.docx';
            $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
            $objWriter->save($filename);

            // 检查是否通过HTTPS访问
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://';
            // 获取主机名
            $host = $_SERVER['HTTP_HOST'];
            // 组合成完整的URL
            $currentDomain = $protocol . $host;
            return json(['code' => 1, 'msg' => '打印成功', 'data' => $currentDomain . '/' . $filename]);
        } catch (Exception $e) {
            echo $e->getMessage();
            return json(['code' => 0, 'msg' => '打印失败']);
            // die('生成文档失败: ' . $e->getMessage());
        }
    }
}
